package main

import(
	"fmt"
	"os"
	"log"
	"github.com/joho/godotenv"
	"github.com/go-chi/chi/v5"
	"net/http"
	"github.com/go-chi/cors"
	"gitee.com/xunyiovo/rssagg/internal/database"
	_ "github.com/lib/pq"
	"database/sql"
)

type apiConfig struct{
	DB *database.Queries
}
func main(){
	// Load will read your env file(s) and load them into ENV for this process.
	// So envs of shell remain unchanged
	err := godotenv.Load(".env")
	if err != nil{
		log.Fatal("loading env file err")
	}
	
	portString := os.Getenv("PORT")
	if portString == ""{
		log.Fatal("port is not found in env")
	}
	dbUrl := os.Getenv("DB_URL")
	if dbUrl == ""{
		log.Fatal("DB_URL is not found in env")
	}
	conn, err := sql.Open("postgres",dbUrl)
	if err != nil{
		log.Fatal("Fail to connect database: ",err)
	}

	apiCfg := apiConfig{
		DB: database.New(conn),
	}


	router := chi.NewRouter()
	router.Use(cors.Handler(cors.Options{
		AllowedOrigins: 	[]string{"https://*","http://*"},
		AllowedMethods: 	[]string{"GET","POST","DELETE","PUT","OPTIONS"},
		AllowedHeaders: 	[]string{"*"},
		ExposedHeaders: 	[]string{"Link"},
		AllowCredentials: 	false,
		MaxAge:				300,
	}))
	routerV1 := chi.NewRouter()
	routerV1.Get("/ready",handlerReadiness)
	routerV1.Get("/error",handlerError)
	routerV1.Post("/users",apiCfg.handlerCreateUser)
	router.Mount("/v1",routerV1)
	svr := &http.Server{
		Handler : router,
		Addr    : ":" + portString,
	}

	fmt.Println("Server starting on port " + portString)
	err = svr.ListenAndServe()
	if err != nil{
		log.Fatal(err)
	}

}
